package cn.beforedark.yygh.userinfo.service.impl;

import cn.beforedark.yygh.common.exception.YyghException;
import cn.beforedark.yygh.common.util.JwtHelper;
import cn.beforedark.yygh.enums.AuthStatusEnum;
import cn.beforedark.yygh.model.userinfo.UserInfo;
import cn.beforedark.yygh.userinfo.mapper.UserInfoMapper;
import cn.beforedark.yygh.userinfo.service.UserInfoService;
import cn.beforedark.yygh.dto.user.UserAuthDto;
import cn.beforedark.yygh.dto.user.LoginDto;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private HttpServletRequest request;

    @Override
    public Map<String, Object> login(LoginDto loginDto) {
        // 1. 非空校验
        String phone = loginDto.getPhone();
        String code = loginDto.getCode();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException("手机号或验证码错误");
        }
        // 2. 校验验证码
        String redisCode = redisTemplate.opsForValue().get("code:phone:" + phone);
        if (redisCode == null) {
            throw new YyghException("验证码已过期");
        }
        if (!code.equals(redisCode)) {
            throw new YyghException("验证码错误");
        }
        UserInfo userInfo = null;
        /*
        String openid = loginDto.getOpenid();
        UserInfo userInfo = null;
        System.out.println("-------------------" + openid);
        if (StringUtils.isEmpty(openid)) {
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone);
            userInfo = baseMapper.selectOne(queryWrapper);
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        } else {
*/
        // 3. 验证码校验
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        userInfo = baseMapper.selectOne(wrapper);
        if (userInfo == null) {
            // QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            // queryWrapper.eq("openid", openid);
            // userInfo = baseMapper.selectOne(queryWrapper);
            userInfo = new UserInfo();
            userInfo.setName("");
            userInfo.setPhone(phone);
            userInfo.setStatus(1);
            baseMapper.insert(userInfo);
        }  /*else {
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            // queryWrapper.eq("openid", openid);
            UserInfo userInfo1 = baseMapper.selectOne(queryWrapper);
            userInfo.setNickName(userInfo1.getNickName());
            userInfo.setOpenid(userInfo1.getOpenid());
            baseMapper.updateById(userInfo);
            baseMapper.deleteById(userInfo1.getId());
        }
         }
         */
        // 是否被禁用
        if (userInfo.getStatus() == 0) {
            throw new YyghException("用户锁定中");
        }
        Map<String, Object> result = new HashMap<>();
        String nickName = userInfo.getNickName();
        if (StringUtils.isEmpty(nickName)) {
            nickName = userInfo.getPhone();
        }
        result.put("name", nickName);
        String token = JwtHelper.createToken(userInfo.getId(), nickName);
        result.put("token", token);

        return result;
    }

    @Override
    public Map<String, Object> detail(Long id) {
        UserInfo userInfo = baseMapper.selectById(id);
        if(userInfo == null){
            // throw YyghException.token("用户不存在");
            return null;
        }
        // List<Patient> patients = patientService.selectList(id);
        Map<String, Object> map = new HashMap<>(2);
        map.put("userInfo", userInfo);
        // map.put("patients", patients);
        return map;
    }

    @Override
    public Long getThisUserId() {
        try {
            String token = request.getHeader("token");
            Long userId = JwtHelper.getUserId(token);
            return userId;
        } catch (Exception e) {
            throw YyghException.token("token 无效");
        }
    }

    public void updateUserAuth(Long userId, UserAuthDto userAuthDto) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setName(userAuthDto.getName());
        userInfo.setCertificatesType(userAuthDto.getCertificatesType());
        userInfo.setCertificatesNo(userAuthDto.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthDto.getCertificatesUrl());
        userInfo.setUpdateTime(new Date());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        baseMapper.updateById(userInfo);
    }
}
